# 不平衡数据集
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC


def load_data(input_file):
    X = []
    y = []
    with open(input_file,'r') as f:
        for line in f.readlines():
            data = [float(x) for x in line.split(",") ]
            X.append(data[:-1])
            y.append(data[-1])

    X = np.array(X)
    y = np.array(y)
    return X,y


# 加载数据
input_file = "F:/python学习资料/Python-Machine-Learning-Cookbook-master/" \
             "Chapter03/data_multivar_imbalance.txt"
X,y = load_data(input_file)
print(X[:5])
print(y[:5])

# 基于y值把数据分类
class_0 = np.array([X[i] for i in range(len(X)) if y[i] == 0])
class_1 = np.array([X[i] for i in range(len(X)) if y[i] == 1])

# 画出输入数据
plt.figure()
plt.scatter(class_0[:,0],class_0[:,1],facecolors='black',edgecolors='black',marker='s')
plt.scatter(class_1[:,0],class_1[:,1],facecolors='None',edgecolors='black',marker='s')
plt.title("Input data")
plt.show()

# 使用线性核函数
from sklearn import model_selection
X_train,X_test,y_train,y_test = model_selection.train_test_split(X,y,random_state=5,test_size=0.25)
params = {'kernel':'linear','class_weight':'balanced'}
classifier = SVC(**params,gamma='auto')
classifier.fit(X_train,y_train)

# 然后打印出分类报告
from sklearn.metrics import classification_report
target_names = ['Class-'+str(int(i)) for i in set(y)]
print("\n"+"#"*30)
print("\n线性核函数在训练集上的表现")
print(classification_report(y_train,classifier.predict(X_train),target_names=target_names))
print("#"*30+'\n')
print('\n线性核函数在测试集上的表现')
print(classification_report(y_test,classifier.predict(X_test),target_names=target_names))
print("#"*30)

# 使用高斯核半径
classifier_rbf = SVC(gamma='auto')
classifier_rbf.fit(X_train,y_train)
print("\n"+"#"*30)
print("\n高斯核函数在训练集上的表现")
print(classification_report(y_train,classifier_rbf.predict(X_train),target_names=target_names))
print("#"*30+'\n')
print('\n高斯核函数在测试集上的表现')
print(classification_report(y_test,classifier_rbf.predict(X_test),target_names=target_names))
print("#"*30)

